/**   
 * Copyright © 2016 北京之洲科技有限责任公司. All rights reserved.
 * 
 * @Title: ZLPJCrawlOfAutoHome.java 
 * @Prject: carfactory
 * @Package: com.zizo.autohome.bbs.zlfk.crawl 
 * @Description: 
 * @author: Alexis  
 * @email heyan0227@outlook.com
 * @date: 2016年8月16日 下午6:26:16 
 * @version: V1.0   
 */
package com.zizo.autohome.bbs.zlfk.crawl;

import java.sql.Connection;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.zizo.autohome.bbs.zlfk.dao.ZLFKDaoOfAutoHome;
import com.zizo.util.ConnectionPool;
import com.zizo.util.DocUtil;
import com.zizo.util.Util;

/**
 * @ClassName: ZLPJCrawlOfAutoHome
 * @Description:
 * @author: Alexis
 * @date: 2016年8月16日 下午6:26:16
 */
public class ZLPJCrawlOfAutoHome implements Runnable {
	private String id;
	private ZLFKDaoOfAutoHome dao;

	public ZLPJCrawlOfAutoHome(String id, ZLFKDaoOfAutoHome dao) {
		super();
		this.id = id;
		this.dao = dao;
	}

	public void getItems() {
		try {
			String url = "http://club.autohome.com.cn/bbs/forum-" + this.id + "-1.html?type=101";
			Document doc = DocUtil.getDoc(url);
			if (doc == null) {
				return;
			}
			int page = 1;
			if (doc.select("div.pagearea span.fr").size() > 0) {
				page = Integer.parseInt(
						Util.getMatched(doc.select("div.pagearea span.fr").text(), "(共)(\\d{1,})(页)").group(2));
			}
			for (int i = 1; i < page + 1; i++) {
				String link = "http://club.autohome.com.cn/bbs/forum-" + this.id + "-" + i + ".html?type=101";
				Document content = null;
				if (i == 1) {
					content = doc;
				} else {
					content = DocUtil.getDoc(link);
				}
				Elements lis = content.select("div#subcontent dl.list_dl:not(.bluebg)");
				for (Element li : lis) {
					String insertid = li.select("a.a_topic").attr("href").split("-")[3];
					dao.insertID(insertid);
				}
			}
		} catch (Exception e) {
			System.out.println(this.id);
			e.printStackTrace();
		}
	}

	public void run() {
		getItems();
		System.out.println(this.id);
	}

	public static void main(String[] args) {
		Connection conn = ConnectionPool.getConnection("autohome", "carvoice.tpddns.cn", "3308");
		Connection core = ConnectionPool.getConnection("autohome_old", "carvoice.tpddns.cn", "3308");
		ZLFKDaoOfAutoHome dao = new ZLFKDaoOfAutoHome(conn, core);
		ZLPJCrawlOfAutoHome crawl = new ZLPJCrawlOfAutoHome("c-364", dao);
		crawl.getItems();
	}
}
